<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="商户名称" prop="mchName">
        <el-input
          v-model="queryParams.mchName"
          placeholder="请输入商户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户号" prop="mchNo">
        <el-input
          v-model="queryParams.mchNo"
          placeholder="请输入商户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder=""
          clearable
        >
          <el-option
            v-for="dict in dict.type.paysystem_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mch:edit']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mch:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mch:edit']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mch:query']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column  v-if="checkPermi(['platop'])" label="代理商" align="center" prop="parentName" />
      <el-table-column label="商户号" align="center" prop="mchNo" />
      <el-table-column label="商户名称" align="center" prop="mchName" />
      <el-table-column label="商户简称" align="center" prop="mchShortName" />
      <el-table-column label="状态" align="center" prop="state" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.paysystem_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="商户备注" align="center" prop="remark" />
      <el-table-column label="初始用户ID" align="center" prop="initUserId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mch:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mch:edit']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="resetGoogle(scope.row)"
            v-hasPermi="['mch:edit']"
          >重置谷歌</el-button>
        </template>
      </el-table-column>
      <el-table-column label="支付操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePayIf(scope.row)"
            v-hasPermi="['mch:edit']"
          >支付通道</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleMchConfig(scope.row)"
            v-hasPermi="['mch:config']"
          >对接参数</el-button>
        </template>
      </el-table-column>
      <el-table-column label="VA操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleVA(scope.row)"
            v-hasPermi="['mch:edit']"
          >VA详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleVAIf(scope.row)"
            v-hasPermi="['mch:edit']"
          >VA通道</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="代理商" prop="parentNo">
          <el-select v-model="form.parentNo" placeholder="绑定代理商" filterable clearable>
            <el-option
              v-for="item in agentList"
              :key="item.agentNo"
              :label="item.agentName"
              :value="item.agentNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商户名称" prop="mchName">
          <el-input v-model="form.mchName" placeholder="请输入商户名称" />
        </el-form-item>
        <el-form-item label="商户简称" prop="mchShortName">
          <el-input v-model="form.mchShortName" placeholder="请输入商户简称" />
        </el-form-item>
        <el-form-item label="登陆账号" prop="loginUserName" v-if="!form.mchNo">
          <el-input v-model="form.loginUserName" placeholder="登陆账号" />
        </el-form-item>
        <el-form-item label="登陆密码" prop="loginPassword">
          <el-input v-model="form.loginPassword" placeholder="登陆密码(默认fusion666)" />
        </el-form-item>
        <el-form-item label="资金密码" prop="loginPassword">
          <el-input v-model="form.payPassword" placeholder="资金密码(默认fusion888)" />
        </el-form-item>
        <el-form-item label="TG群ID" prop="tgChatId">
          <el-input v-model="form.tgChatId" placeholder="" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.paysystem_state"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商户备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入商户备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openIf" width="75%" append-to-body >
      <el-table v-loading="loading" :data="mchIfList" @selection-change="handleSelectionChange">
        <el-table-column label="接口" align="center" prop="key.ifName" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.value.mpId" type="success">已配置</el-tag>
            <el-tag v-else type="danger">未配置</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="通道费率(%)" align="center" prop="key.ifRate" >
        </el-table-column>
        <el-table-column label="商户费率(%)" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.value.rate">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="通道代付费率(%)" align="center" prop="key.ifPayoutRate" >
        </el-table-column>
        <el-table-column label="商户代付费率(%)" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.value.payoutRate">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="value.updateTime" >
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleMchPayIfUpdate(scope.row)"
              v-hasPermi="['mch:edit']"
            >提交</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleMchPayIfDelete(scope.row)"
              v-hasPermi="['mch:edit']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openConfig" width="60%" append-to-body >
      <el-form ref="mchConfig" :model="mchConfig" :rules="rules" label-width="150px">
        <el-form-item label="商户私钥" prop="privateKey">
          <el-input v-model="mchConfig.privateKey" type="textarea" placeholder="商户私钥" />
        </el-form-item>
        <el-form-item label="商户公钥" prop="publicKey">
          <el-input v-model="mchConfig.publicKey" type="textarea" placeholder="商户公钥" />
        </el-form-item>
        <el-form-item label="平台公钥(回调验签)" prop="platPub">
          <el-input v-model="mchConfig.platPub" type="textarea" placeholder="平台公钥" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
        <el-button @click="openConfig = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="VA详情" :visible.sync="openVA" width="55%" append-to-body >
      <el-table v-loading="loading" :data="vaList" @selection-change="handleSelectionChange">
        <el-table-column label="开户银行" align="center" >
          <template slot-scope="scope">
            <span v-if="scope.row.provider =='bison'">贝森银行</span>
            <span v-if="scope.row.provider =='sunpay'">SunPay</span>
          </template>
        </el-table-column>
        <el-table-column label="开户名" align="center" prop="vaName" >
        </el-table-column>
        <el-table-column label="开户状态" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.vaState" placeholder="请选择">
              <el-option
                v-for="item in vaStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
<!--            <el-tag v-if="scope.row.vaState == -2" type="primary">等待提交材料</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == -1" type="primary">已提交材料</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == 0" type="primary">KYC审核中</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == 1" type="success">KYC通过</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == 2" type="danger">KYC失败</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == 3" type="primary">开户中</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == 4" type="success">开户成功</el-tag>-->
<!--            <el-tag v-if="scope.row.vaState == 5" type="danger">开户失败</el-tag>-->
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" >
        </el-table-column>
        <el-table-column label="备注" align="center"  >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="handleKyc(scope.row)"
              v-hasPermi="['mch:edit']"
            >KYC开户</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="editVa(scope.row)"
              v-hasPermi="['mch:edit']"
            >修改信息</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="VA费率" :visible.sync="openIfVA" width="60%" append-to-body >
        <el-tabs v-model="activeVAIfIndex" type="card" @tab-click="handleVAIfClick">
          <template v-for="item in mchVAIfList">
            <el-tab-pane :label="item.key.ifName" :name="index">
              <el-table v-loading="loading" :data="mchVAIfList[activeVAIfIndex].rateList">
                <el-table-column label="功能" align="center" prop="label">
                </el-table-column>
                <el-table-column label="费率(%)" align="center">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.rate">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="扣费下限" align="center">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.min">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="扣费上限" align="center">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.max">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="最低值" align="center">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.start">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="开通时间" align="center"  prop="updateTime">
<!--                  <template slot-scope="scope">-->
<!--                    <el-switch-->
<!--                      v-model="scope.row.enabled"-->
<!--                      active-color="#13ce66"-->
<!--                      inactive-color="#ff4949">-->
<!--                    </el-switch>-->
<!--                  </template>-->
                </el-table-column>
              </el-table>
              <div style="float: right;margin-right: 100px;margin-top: 20px">
                <el-button
                  type="primary" icon="el-icon-check" size="medium"
                  @click="handleMchVAIfUpdate(mchVAIfList[activeVAIfIndex])"
                  v-hasPermi="['mch:edit']"
                >提交</el-button>
              </div>
            </el-tab-pane>
          </template>
        </el-tabs>
    </el-dialog>
    <bison-admin-kyc v-if="bisonShowKyc" ref="bisonAdminKyc"></bison-admin-kyc>
  </div>
</template>

<script>
import {
  listMch,
  getMch,
  delMch,
  addMch,
  updateMch,
  updateMchPayIf,
  mchPayIfList,
  deleteMchPayIf,
  getMchConfig,
  updateMchConfig,
  resetMchGoogle
} from "@/api/fusion/mch";
import {
  getMchVA,
  updateMchVA,
  mchVAIfList,
  updateMchVAIf
} from "@/api/fusion/mchva";
import BisonAdminKyc from "@/views/fusion/va/bison/admin-kyc.vue";
export default {
  name: "Mch",
  dicts: ['paysystem_state'],
  data() {
    return {
      vaStateOptions:[
        {label: '未提交KYC材料', value: -2},
        {label: 'KYC材料已提交', value: -1},
        {label: 'KYC审核中', value: 0},
        {label: 'KYC通过', value: 1},
        {label: 'KYC失败', value: 2},
        {label: '开户中', value: 3},
        {label: '开户成功', value: 4},
        {label: '开户失败', value: 5}
      ],
      bisonShowKyc:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      agentList:[],
      // 商户信息表格数据
      mchList: [],
      mchIfList: [],
      vaName: '',
      vaList:[],
      mchVAIfList:[],
      activeVAIfIndex:0,
      inEditMchNo: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openIfVA:false,
      openIf: false,
      openConfig: false,
      openVA: false,
      // 查询参数
      queryParams: {
        isAsc:'desc',
        orderByColumn:'mch_no',
        pageNum: 1,
        pageSize: 10,
        mchName: null,
        mchShortName: null,
        parentNo: null,
        state: null,
        initUserId: null,
      },
      mchConfig: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mchName: [
          { required: true, message: "商户名称不能为空", trigger: "blur" }
        ],
        mchShortName: [
          { required: true, message: "商户简称不能为空", trigger: "blur" }
        ],
        loginUserName: [
          { required: true, message: "登陆账号不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "商户状态: 0-停用, 1-正常不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  components: {
    BisonAdminKyc
  },
  methods: {
    editVa(data) {
      this.$confirm('修改用户VA信息, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateMchVA(data).then((response)=>{
          this.$modal.msgSuccess(response.msg);
        })
      }).catch(err => {
      })
    },
    handleKyc(va) {
      if(va.provider === 'bison') {
        this.openVA = false
        this.bisonShowKyc = true
        this.$nextTick(()=>{
          this.$refs.bisonAdminKyc.init(va, this.vaName)
        })

      }
    },
    /** 查询商户信息列表 */
    getList() {
      this.loading = true;
      listMch(this.queryParams).then(response => {
        this.mchList = response.rows;
        this.agentList = response.ext.agentList;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        mchNo: null,
        mchName: null,
        mchShortName: null,
        parentNo: null,
        state: null,
        remark: null,
        initUserId: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.mchNo)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleVAIfClick(tab) {
      this.activeVAIfIndex = tab.index
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户信息";
    },
    handleVA(row) {
      this.openVA = true;
      this.vaList = []
      this.vaName = row.mchName
      getMchVA(row.mchNo).then(response => {
        this.vaList = response.data;
      });
    },
    handlePayIf(row) {
      this.mchIfList = []
      this.inEditMchNo = null
      mchPayIfList({mchNo: row.mchNo}).then(response => {
        this.openIf = true;
        this.mchIfList = response.rows
        this.title = "支付配置";
        this.inEditMchNo = row.mchNo
      });
    },
    handleVAIf(row) {
      this.mchVAIfList = []
      this.activeVAIfIndex = '0'
      mchVAIfList(row.mchNo).then(response => {
        this.openIfVA = true;
        // response.data
        for(let i = 0; i < response.data.length; i ++) {
          let d = response.data[i]
          let temp = JSON.parse(d.key.ifParams)
          let myrate = {}
          if(d.value.multiParams) {
            myrate = JSON.parse(d.value.multiParams)
          }
          for(let j = 0; j < temp.length; j++) {
            let d = temp[j]
            let my = myrate[d.key]
            if(my) {
              temp[j] = my
              // d.enable = true
            } else {
              // d.enable = false
            }
          }
          d.mchNo = row.mchNo
          d.rateList = temp
        }
        this.mchVAIfList = response.data
      });
    },
    handleMchConfig(row) {
      this.mchConfig = {}
      getMchConfig(row.mchNo).then(response => {
        this.openConfig = true
        this.mchConfig = response.data
        this.title = "对接参数";
      });
    },
    handleMchVAIfUpdate(data) {
      updateMchVAIf(data).then(response => {
        data.rateList = response.data
        this.$modal.msgSuccess("更新VA费率参数成功");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const mchNo = row.mchNo || this.ids
      getMch(mchNo).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商户信息";
      });
    },
    submitConfigForm() {
      updateMchConfig(this.mchConfig).then(response => {
        this.$modal.msgSuccess("修改对接参数成功");
        this.openConfig = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.mchNo != null) {
            updateMch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    resetGoogle(row) {
      this.$modal.confirm('是否重置商户的谷歌密钥').then(function() {
        return resetMchGoogle(row.mchNo);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mchNos = row.mchNo || this.ids;
      this.$modal.confirm('是否确认删除商户信息编号为"' + mchNos + '"的数据项？').then(function() {
        return delMch(mchNos);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mch/mch/export', {
        ...this.queryParams
      }, `mch_${new Date().getTime()}.xlsx`)
    },
    handleMchPayIfUpdate(data) {
      let d = {}
      d.mpId = data.value.mpId
      d.mchNo = this.inEditMchNo
      d.payifId = data.key.id
      d.rate = data.value.rate
      d.payoutRate = data.value.payoutRate
      if(data.key.ifRate > d.rate) {
        this.$modal.msgError("商户费率不能低于通道成本");
        return
      }
      if(data.key.ifPayoutRate > d.payoutRate) {
        this.$modal.msgError("商户代付费率不能低于代付通道成本");
        return
      }
      updateMchPayIf(d).then(response => {
        this.$modal.msgSuccess("修改成功");
        data.value = response.data
      });
    },
    handleMchPayIfDelete(data) {
      deleteMchPayIf(data.value.mpId).then(response => {
        this.$modal.msgSuccess("删除成功");
        data.value.mpId = null
        data.value.rate = ''
      });
    }
  }
};
</script>
